// 样式到 Tailwind 类名的映射
// 颜色映射表
const colorMap: Record<string, string> = {
  '#ffffff': 'white',
  '#000000': 'black',
  '#333333': 'gray-800',
  '#1890ff': 'blue-500',
  '#f5222d': 'red-500',
  '#52c41a': 'green-500',
  '#faad14': 'yellow-500',
  '#722ed1': 'purple-500',
  '#eb2f96': 'pink-500',
};

// HEX转Tailwind类名
const toTailwindColor = (hex: string) => {
  const normalizedHex = hex.toLowerCase();
  return colorMap[normalizedHex] || `[${hex}]`;
};

// Tailwind类名转HEX
const toHex = (twClass: string) =>
  Object.entries(colorMap).find(([_, v]) => v === twClass)?.[0] || twClass;

// 尺寸单位转换（4px = 1单位）
const pxToUnit = (px: string) => Math.round(parseInt(px.replace('px', '')) / 4).toString();

// 主题色映射表
const themeColorMap: Record<string, string> = {
  primary: 'blue-500',
  success: 'green-500',
  warning: 'yellow-500',
  danger: 'red-500',
  info: 'gray-500',
};

// 预设样式组合
const presetStyleMap: Record<string, string[]> = {
  // 布局预设
  'flex-center': ['flex', 'justify-center', 'items-center'],
  'flex-between': ['flex', 'justify-between', 'items-center'],
  'grid-2-cols': ['grid', 'grid-cols-2', 'gap-4'],
  'grid-3-cols': ['grid', 'grid-cols-3', 'gap-4'],

  // 文本预设
  'text-primary': ['text-base', 'text-gray-900', 'font-medium'],
  'text-secondary': ['text-sm', 'text-gray-600'],
  'text-caption': ['text-xs', 'text-gray-500'],
  'text-title': ['text-xl', 'font-bold', 'text-gray-900'],

  // 响应式预设
  'mobile-hidden': ['hidden', 'md:block'],
  'desktop-only': ['hidden', 'lg:block'],
  'mobile-only': ['block', 'md:hidden'],

  // 交互预设
  'hover-scale': ['transform', 'hover:scale-105', 'transition-transform'],
  'hover-shadow': ['hover:shadow-lg', 'transition-shadow'],
  'active-scale': ['transform', 'active:scale-95', 'transition-transform'],
};

// 扩展样式映射表
const styleToTailwindMap: Record<string, (value: string) => string> = {
  color: (value) => `text-${toTailwindColor(value)}`,
  backgroundColor: (value) => `bg-${toTailwindColor(value)}`,
  fontSize: (value) => {
    const size = pxToUnit(value);
    const sizeMap: Record<string, string> = {
      '3': 'text-xs',
      '3.5': 'text-sm',
      '4': 'text-base',
      '4.5': 'text-lg',
      '5': 'text-xl',
      '6': 'text-2xl',
    };
    return sizeMap[size] || `text-[${value}]`;
  },
  padding: (value) => `p-${pxToUnit(value)}`,
  margin: (value) => `m-${pxToUnit(value)}`,
  display: (value) => (value === 'flex' ? 'flex' : value),
  flexDirection: (value) => (value === 'column' ? 'flex-col' : 'flex-row'),
  justifyContent: (value) => {
    const justifyMap: Record<string, string> = {
      'flex-start': 'justify-start',
      'flex-end': 'justify-end',
      center: 'justify-center',
      'space-between': 'justify-between',
      'space-around': 'justify-around',
    };
    return justifyMap[value] || `justify-${value}`;
  },
  alignItems: (value) => {
    const alignMap: Record<string, string> = {
      'flex-start': 'items-start',
      'flex-end': 'items-end',
      center: 'items-center',
      stretch: 'items-stretch',
      baseline: 'items-baseline',
    };
    return alignMap[value] || `items-${value}`;
  },
  overflow: (value) => `overflow-${value}`,
  preset: (value) => {
    const presetClasses = presetStyleMap[value];
    return presetClasses ? presetClasses.join(' ') : value;
  },
  themeColor: (value) => {
    const color = themeColorMap[value];
    return color ? `text-${color}` : `text-${value}`;
  },
  themeBackground: (value) => {
    const color = themeColorMap[value];
    return color ? `bg-${color}` : `bg-${value}`;
  },
  gap: (value) => `gap-${pxToUnit(value)}`,
  gridCols: (value) => `grid-cols-${value}`,
  gridRows: (value) => `grid-rows-${value}`,
  paddingX: (value) => `px-${pxToUnit(value)}`,
  paddingY: (value) => `py-${pxToUnit(value)}`,
  marginX: (value) => `mx-${pxToUnit(value)}`,
  marginY: (value) => `my-${pxToUnit(value)}`,
  fontWeight: (value) => `font-${value}`,
  lineHeight: (value) => `leading-${value}`,
  letterSpacing: (value) => `tracking-${value}`,
  textAlign: (value) => `text-${value}`,
  borderRadius: (value) => `rounded-${pxToUnit(value)}`,
  borderWidth: (value) => `border-${pxToUnit(value)}`,
  borderColor: (value) => `border-${toTailwindColor(value)}`,
  opacity: (value) => `opacity-${parseInt(value) * 100}`,
  shadow: (value) => `shadow-${value}`,
  transition: (value) => `transition-${value}`,
  transform: (value) => `transform-${value}`,
  cursor: (value) => `cursor-${value}`,
};

interface IStyleTransformer {
  // 将样式对象转换为 Tailwind 类名
  toStyle: (style: Record<string, any>) => string;
  // 合并多个样式对象并转换为 Tailwind 类名
  mergeClassesToStyle: (styles: string[]) => string;
  // 处理伪类和响应式类名
  extractSpecialClasses: (style: Record<string, any>) => {
    base: string[];
    hover: string[];
    responsive: Record<string, string[]>;
  };
}

export const StyleTransformer: IStyleTransformer = {
  toStyle: (style) => {
    const classes: string[] = [];
    Object.entries(style).forEach(([key, value]) => {
      const converter = styleToTailwindMap[key];
      if (converter) {
        classes.push(converter(value as string));
      }
    });
    return classes.join(' ');
  },

  mergeClassesToStyle: (styles) => {
    const mergedStyle = styles.reduce((acc, style) => {
      try {
        const styleObj = JSON.parse(style);
        return { ...acc, ...styleObj };
      } catch (e) {
        console.warn('Style 解析失败:', e);
        return acc;
      }
    }, {});
    return StyleTransformer.toStyle(mergedStyle);
  },

  extractSpecialClasses: (style) => {
    const result = {
      base: [] as string[],
      hover: [] as string[],
      responsive: {
        sm: [] as string[],
        md: [] as string[],
        lg: [] as string[],
        xl: [] as string[],
      },
    };

    Object.entries(style).forEach(([key, value]) => {
      const converter = styleToTailwindMap[key];
      if (converter) {
        if (key.startsWith('hover')) {
          result.hover.push(converter(value as string));
        } else if (key.startsWith('sm:')) {
          result.responsive.sm.push(converter(value as string));
        } else if (key.startsWith('md:')) {
          result.responsive.md.push(converter(value as string));
        } else if (key.startsWith('lg:')) {
          result.responsive.lg.push(converter(value as string));
        } else if (key.startsWith('xl:')) {
          result.responsive.xl.push(converter(value as string));
        } else {
          result.base.push(converter(value as string));
        }
      }
    });

    return result;
  },
};
